package dse.messages.multiversion;

import dse.Experiment;
import dse.ExperimentRecorder;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;

public class RequestVersionV3MessageHandler extends MessageSender implements MessageHandler {
	private VersionReader versionReader;
	
	public RequestVersionV3MessageHandler (
			Experiment experiment, 
			VersionReader versionReader
			)
	{
		super(experiment);
		
		this.versionReader = versionReader;
	}
	
	
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgIntrpt: " + message, time);
		versionReader.readVersion(recorder, -1, time);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message, double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.RequestVersionV3) {
			recorder.warn(
					"RequestVersionV3MessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}			
		// What do we know about the share?
		int sequence = message.to().sequence();
		
		// Does the receiver have the share?
		
		// Then we need to send a new message BACK (thats why to and from
		// are reversed!
		Message m = super.createVersionResponseV3Message(
				message.to(), message.from(), sequence, message.purpose(), versionReader);
		recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
		
	}
}
